<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="layui/css/layui.css">
  <style>
    .title {
      font-size: 24px;
      border: 1px solid #00F7DE;
      width: 300px;
    }

    .desc {
      font-size: 18px;
      border: 1px solid #00F7DE;
      width: 300px;
      min-height: 100px;
    }

    .edit-field {
      border: 1px solid #f00;
    }
  </style>
</head>
<body>

<h1>详情页</h1>
<div class="show">
  <div class="show-field">
    <div id="title"  class="title">Loading...</div>
    <div id="desc"  class="desc">加载中</div>
  </div>
  <div class="edit-field" style="display: none">
    <input id="title1" type="text" value="" class="title">
    <br>
    <textarea id="desc1" class="desc"></textarea>
  </div>
  <div>
    <label>
      <input type="checkbox" id="completed">
      <span></span>
    </label>
  </div>
  <div>
    <button type="button" class="layui-btn update-btn">修改</button>
    <button type="button" class="layui-btn layui-btn-danger">删除</button>
  </div>
</div>

<script src="layui/layui.js"></script>
<script src="js/zepto.js"></script>
<script>
  $.ajax({
    url: `https://api.yizhanketang.cn/api/v1/todos/${getQuery('id')}`,
    success(res) {
      console.log(res.data)
      // console.log(res)
      // const { data, code } = res
      // console.log(data, code)
      const { completed, content, description } = res.data

      // console.log(completed)
      // console.log(content)
      // console.log(description)

      $('#title').text(content)
      $('#title1').val(content)
      $('#desc').text(description)
      $('#desc1').val(description)
      $('#completed').prop('checked', completed)
        .next().text(completed ? '已完成' : '未完成')
    }
  })

  $('.update-btn').on('click', function () {

    if ($(this).html() === '修改') {
      $(this).html('保存')
      $('.edit-field').show()
      $('.show-field').hide()
    } else {
      // ajax
      $.ajax({
        type: 'POST',
        url: `https://api.yizhanketang.cn/api/v1/todos/${getQuery('id')}`,
        data: {
          content: $('#title1').val(),
          description: $('#desc1').val()
        },
        success(res) {
          console.log(res)

          location.reload()

          // $(this).html('保存')
          // $('.edit-field').show()
          // $('.show-field').hide()
        }
      })

      console.log('保存')
    }


    // 保存 ajax
  })




  function getQuery(key) {
    let arr = location.search.slice(1).split('&')
    for (let item of arr) {
      let item_temp = item.split('=')

      if (item_temp[0] === key) {
        return item_temp[1]
      }
    }
  }

</script>
</body>
</html>